﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Reflection;
using Telerik.Web.UI;

namespace atmGen
{
    [Serializable()]
    public class fmfunc
    {

        public const string GroupKey = "#Group";

        public  enum fmControlProp
        {
            Normal,
            ReadOnly,
            Visible,
            Enable
        }
        public  enum fmControlType
        {
            None,
            SDSTextBox = 1,
            SDSDropDownList = 2,
            BothSDSTextDDL = SDSTextBox | SDSDropDownList

        }
        public fmfunc()
        {
        }
        public static string[] RemoveDuplicates(string[] myList)
        {
            System.Collections.ArrayList newList = new System.Collections.ArrayList();

            foreach (string str in myList)
                if (!newList.Contains(str))
                    newList.Add(str);
            return (string[])newList.ToArray(typeof(string));
        }

        public static string DateTimeFormat
        {
            get { return "dd/MM/yyyy"; }
        }
        /// <summary>
        /// Call menu & toolbar menu for clear variable pass from/to form screen
        /// </summary>
        public static void ClearFormParam()
        {
            ApproveSelRow = -1;
            ApproveID = 0;
        }
        public static int ApproveSelRow
        {
            get { return HttpContext.Current.Session["ApproveSelRow"] == null ? -1 : (int)HttpContext.Current.Session["ApproveSelRow"]; }
            set { HttpContext.Current.Session["ApproveSelRow"] = value; }
        }
        public static int ApproveID
        {
            get { return HttpContext.Current.Session["ApproveID"]==null ? 0 : (int)HttpContext.Current.Session["ApproveID"]; }
            set { HttpContext.Current.Session["ApproveID"] = value; }
        }
        public static void setlnkCommandPost(LinkButton lnkPrintPreview, LinkButton lnkPrint, LinkButton lnkCancel,
                     LinkButton lnkSendBack,   LinkButton lnkDraft, LinkButton lnkSave, LinkButton lnkClose)
        {
            int leftPost = 375 + (lnkClose.Visible ? 20 : 0) + 68;
            bool[] vislnks = { lnkClose.Visible, lnkSave.Visible, lnkDraft.Visible,lnkSendBack.Visible, lnkCancel.Visible, lnkPrint.Visible, lnkPrintPreview.Visible };
            LinkButton[] lnks = { lnkClose, lnkSave, lnkDraft,lnkSendBack, lnkCancel, lnkPrint, lnkPrintPreview };
            int[] adj = { 0, -5, -9, 0, 0,0, 30, 0, 0 };
            lnkClose.Width = 70;
            foreach (LinkButton lnk in lnks) { lnk.Visible = false; }
            int cnt = vislnks.Length;

            for (int i = 0; i < cnt; ++i)
            {
                if (vislnks[i])
                {
                    lnks[i].Visible = true;
                    leftPost -= (adj[i] + 72/*68*/);
                    lnks[i].Style.Add("left", leftPost.ToString() + "px");
                }
            }
        }
        public static bool isRefresh(string imgRefreshName)
        {
            HttpRequest request = HttpContext.Current.Request;
            //check if imgRefresh onclick
            // isThisPostBack = true if imgRefresh is clicked
            if (request.RequestType.ToUpper() != "POST")
            {
                return false;
            }
            string req = request.Params[0].ToString();
            return (req.IndexOf(imgRefreshName, StringComparison.OrdinalIgnoreCase) >= 0);//"$imgRefresh"

        }
        public static bool isThisPostBack(string pageID)
        {
            HttpRequest request = HttpContext.Current.Request;

            if (request.RequestType.ToUpper() != "POST")
            {
                return false;
            }
            string req = request.Params[0].ToString();
            return (req.IndexOf(pageID, StringComparison.OrdinalIgnoreCase) >= 0);

        }
        public static bool isHWGridRequest(string gridPSResult1ID)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request.RequestType.ToUpper() != "POST")
            {
                return false;
            }
            string req = request.Params[0].ToString();
            return (req.IndexOf(gridPSResult1ID, StringComparison.OrdinalIgnoreCase) >= 0);

        }
        public static bool isHWGridRequest(string pageID, string gridPSResult1ID)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request.RequestType.ToUpper() != "POST")
            {
                return false;
            }
            string req = request.Params[0].ToString();
            return (req.IndexOf(pageID, StringComparison.OrdinalIgnoreCase) >= 0
             && req.IndexOf(gridPSResult1ID, StringComparison.OrdinalIgnoreCase) >= 0);

        }
        public static DateTime? ddmmyyyyToDateTimeENG(string ddmmyyyy)
        {
            if (string.IsNullOrEmpty(ddmmyyyy)) { return null; }
            System.Globalization.CultureInfo culinfo = new System.Globalization.CultureInfo("th-TH");
            string[] dmy = (ddmmyyyy.Replace(" ","").Replace("-","/")+"//").Split('/');
            //check year yy or yyyy
            int yyyy = int.Parse(dmy[2]);
            if (yyyy<100)
            {//yy
                int yy = yyyy;
                if (yy < 43) //US
                { dmy[2] = System.DateTime.Today.Year.ToString().Substring(0, 2) + dmy[2]; }
                else//TH
                { dmy[2] = (System.DateTime.Today.Year+543).ToString().Substring(0, 2) + dmy[2]; }
            }
            yyyy = int.Parse(dmy[2]);
            //yyyy
            if (Math.Abs(System.DateTime.Today.Year - yyyy) <= 100)
            {//ค.ศ.
                return new System.DateTime(yyyy, int.Parse(dmy[1]), int.Parse(dmy[0]));
            }
            else
            {//พ.ศ
                return new System.DateTime(yyyy, int.Parse(dmy[1]), int.Parse(dmy[0]), new System.Globalization.ThaiBuddhistCalendar());
            }
            
            
        }
        public static GridViewRow selectRowFromLink(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow row = null;
            try
            {
                atmGen.PropByName objByName = new atmGen.PropByName(e.CommandSource);

                //if (e.CommandSource.GetType().Equals(typeof(LinkButton)))
                //{
                //     row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                //}
                //else if (e.CommandSource.GetType().Equals(typeof(ImageButton)))
                //{
                //     row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
                //}
                row = (GridViewRow)objByName.GetValue("NamingContainer");

                ((GridView)sender).SelectedIndex = row == null ? 0 : row.RowIndex;
                
            }
            catch { };
            return row;
        }
        /// <summary>
        /// This function can call from other page
        /// return input field list
        /// </summary>
        /// <returns></returns>
        public static atmGen.atmFieldList CollectFormData(string[] dbFields, Control[] fmControl)
        {
            //string[] Fields = { "T1_LocationInstall", "T1_AddrNumber_EN", "T1_AddrNumber_TH", "T1_AmphurID", "T1_BuildginName_EN"
            //                      , "T1_BuildingName_TH", "T1_LocationInstall" };//test duplicate (update) T1_LocationInstall
            //Control[] fmControl = { Ttxt_T1_PlaceInstall };
            atmGen.atmFieldList atmfld = new atmGen.atmFieldList();
            int cnt = dbFields.Length;
            Array.Resize<Control>(ref fmControl, dbFields.Length);
            for (int i = 0; i < cnt; ++i)
            {
                string fieldVal = atmGen.atmData.getFormValue(fmControl[i]);
                atmfld.setValue(dbFields[i].ToString(), fieldVal);
            }
            return atmfld;
        }
        public static void atmFieldListToData(string[] dbFields, atmGen.atmFieldList atmfld, object data)
        {
            atmGen.PropByName propname = new atmGen.PropByName(data);
            //string[] Fields = { "T1_LocationInstall", "T1_AddrNumber_EN", "T1_AddrNumber_TH", "T1_AmphurID"
            //                      , "T1_BuildginName_EN", "T1_BuildingName_TH" };
            //atmGen.atmFieldList atmfld = CollectFormData();
            foreach (string field in dbFields)
            {
                //read form field to database field
                object frmValue = atmfld.getValue(field);
                propname.SetValue(field, frmValue);
            }
        }
        public static void FillInForm(object dbtable, object[] fmControl, string[] dbFieldName)
        {
            //screen form fields
            //Control[] fmControl = { Ttxt_R,Ttxt_T1_PlaceInstall,Ttxt_PointInstallName,Ttxt_InstallCodeName,Ttxt_T1_AddrNumber_TH,
            //                           Ttxt_T1_Co2WorkTel,Ttxt_T1_Co2Moblie,Ttxt_T1_Co2Fax};
            //Control[] fmControl2 = { Ttxt_R1F1, Ttxt_R1F2, ddl_R2F1, SDSDropDownList1, SDSDropDownList2, Ttxt_R3F2, 
            //                          ddl_R9F3, ddl_R10F1, ddl_R10F2, ddl_R10F3, };
            atmGen.PropByName propname = new atmGen.PropByName(dbtable);

            int cnt = Math.Max(dbFieldName.Length, fmControl.Length);
            for (int i = 0; i < cnt; ++i)
            {
                atmGen.atmData.setFormValue(fmControl[i], propname.GetValue(dbFieldName[i].ToString()).ToString());
            }
        }
        public static bool FillInDatabase(object dbtable, object[] fmControl, string[] dbFieldName)
        {
            string msg = "";
            atmGen.PropByName DBByName = new atmGen.PropByName(dbtable);
            int cnt = System.Math.Min(fmControl.Length, dbFieldName.Length);
            for (int i = 0; i < cnt; ++i)
            {
                string dbFiels = dbFieldName[i];
                try
                {
                    if (fmControl[i] is Control)
                    {
                        DBByName.SetValue(dbFiels, atmGen.atmData.getFormValue(fmControl[i]));
                    }
                    else
                    {//Convert.ChangeType(ctrl, typeof(string)).ToString()
                        DBByName.SetValue(dbFiels, fmControl[i]);
                    }
                }
                catch (Exception ex) { msg = ex.Message; return false; }
            }
            return true;
        }
        /// <summary>
        /// *******  This method is under condition controlID = "Prefix_" + DatabaseFieldName. *********
        ///                         Prefix include single "_". Ex: TXT_ -> correct , TXT_BB_ -> Error
        /// </summary>
        /// <param name="spDatain"></param>
        /// <param name="SaveMode"></param>
        public static void FillInFormTo(object spDatain,object[] fmControl)
        {
            FillInFormTo(spDatain, false, fmControl);//Database to form
        }
        public static void FillInFormTo(object spDatain, bool SaveMode, object[] fmControl)
        {//@@@@  ยังไม่ได้ Test ลองดู
            if (spDatain == null) { return; }
            object spData = null;
            if (spDatain is Array)
            {
                MsgBox(" : FillInForm : not support array");
            }
            else { spData = spDatain; }
            //screen form fields
            atmGen.PropByName DBByName = new atmGen.PropByName(spData);
            string msg = "";
            int cnt = fmControl.Length;
            if (SaveMode)
            {
                for (int i = 0; i < cnt; ++i)
                {
                    if (fmControl[i] is Control)
                    {
                        string id = ((Control)fmControl[i]).ID;
                        string dbFiels = id.Substring(id.IndexOf('_') + 1);
                        try
                        {
                            DBByName.SetValue(dbFiels, atmGen.atmData.getFormValue(fmControl[i]));
                        }
                        catch (Exception ex) { msg += (id + " , "); }
                    }
                }
            }
            else
            {
                for (int i = 0; i < cnt; ++i)
                {
                    if (fmControl[i] is Control)
                    {
                        string id =((Control) fmControl[i]).ID;
                        id = id.Substring(id.IndexOf('_') + 1);
                        try
                        { 
                            string txt = DBByName.GetValue(id).ToString();
                            if (DBByName.GetValue(id).GetType().ToString() == "System.Decimal")
                            {
                                txt = Util.formatnumber(txt, 3);
                            }
                           
                            atmGen.atmData.setFormValue(fmControl[i], txt);
                        }
                        catch (Exception ex) { msg += (id + " , "); }
                    }
                }
            }
            //if (msg != "") { MsgBox("Field Error: " + msg); }
        }
        public static void RemoveAt2<T>(ref T[] array, int index)
        {
            T[] newArray = new T[array.Length - 1];
            Array.Copy(array, 0, newArray, 0, index);
            Array.Copy(array, index + 1, newArray, index, newArray.Length - index);
            array = newArray;
        }
        public static void setPropControlInPnl(Control[] pControls, fmControlType ctrltype, fmControlProp ctrlProp, bool propValue)
        {

            if (ctrlProp == fmControlProp.Visible)
            {
                try
                {
                    foreach (Control ctrl in pControls)
                    {
                        ctrl.Visible = propValue;
                    }
                }
                catch { }
                return;
            }
            foreach (Control ctrl in pControls)
            {
                setPropControlInPnl( ctrl, ctrltype, ctrlProp,  propValue);
            }
        }
        public static void setPropControlInPnl(Control pControls,fmControlType ctrltype,fmControlProp ctrlProp, bool propValue)
        {
            bool getText = ((ctrltype & fmControlType.SDSTextBox)== fmControlType.SDSTextBox);
            bool getDDL = ((ctrltype & fmControlType.SDSDropDownList) == fmControlType.SDSDropDownList);

            PropByName pname = null;
            foreach (Control ctrl in pControls.Controls)
            {
                if (ctrl.HasControls()) { setPropControlInPnl(ctrl, ctrltype, ctrlProp,propValue); }
            }
            return;
        }
      
        public static void setReadOnlyAll( Control[] controls, bool ReadOnlyAll) {
            
         //   if (!control.HasControls()) { return; }
            foreach (Control _Ctrl in controls)
            {
                try
                {
                    if (_Ctrl is TextBox) { ((TextBox)_Ctrl).ReadOnly = ReadOnlyAll; }
                    else if (_Ctrl is DropDownList) { ((DropDownList)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is CheckBox) { ((CheckBox)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is CheckBoxList) { ((CheckBoxList)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is RadioButton) { ((RadioButton)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is RadioButtonList) { ((RadioButtonList)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is GridView) { ((GridView)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is FileUpload) { ((FileUpload)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is Button) { ((Button)_Ctrl).Enabled = !ReadOnlyAll; }
                    else if (_Ctrl is ListBox) { ((ListBox)_Ctrl).Enabled = !ReadOnlyAll; }
                    if (_Ctrl.HasControls()) {
                        List<Control> ctrl =new List<Control>();
                        foreach(Control _Ctrl2 in _Ctrl.Controls){
                        ctrl.Add(_Ctrl2);
                        }
                        
                        setReadOnlyAll(ctrl.ToArray(), ReadOnlyAll); }
                }
                catch { }
                
            }
           
        }
        public static void ControlInPnl(ref List<Control> chCtrl, Control pControls, bool getText, bool getDDL)
        {
            foreach (Control ctrl in pControls.Controls)
            {
                if (ctrl.HasControls()) { ControlInPnl(ref chCtrl, ctrl, getText, getDDL); }
            }
        }
        public static Control[] ControlInPnl(Control Controls, bool getText, bool getDDL)
        {
            List<Control> Ctrls = new List<Control>();
            ControlInPnl(ref Ctrls, Controls, getText, getDDL);
            return Ctrls.ToArray();
        }

        public static void MsgBox(string msg)
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page != null)
            {
                Util.jsAlert(page, page.ClientID.ToString() + msg);
            }

        }
        /////Dadabase  /////
        /*
        public static string DBsaveRegState(int ApproveID, atm_Gen.GNStates newstate, bool IsDraft, string Remark)
        {
            wsv Client = new wsv();
            if (ApproveID < 1) { return ""; }
            //read all reg in approve
            Tbl_Approve_Mapping[] AppMap = Client.Tbl_Approve_MappingFactoryGetAllByFieldName(Tbl_Approve_MappingFields.ApproveID, ApproveID);
            string msg = "";

            //update reg statue
            if (string.IsNullOrEmpty(msg))
            {
                foreach(Tbl_Approve_Mapping appm in AppMap)
                {
                    Tbl_Approve_Mapping amap = appm;
                    amap.ApproveID = ApproveID;
                    //update reg
                    if (string.IsNullOrEmpty(msg))
                    {
                        Tbl_Registion[] regData = Client.Tbl_RegistionFactoryGetAllByFieldName(Tbl_RegistionFields.T1_RegistionID, amap.T1_RegistionID);
                        if (regData.Length > 0)
                        {
                            regData[0].T1_Status_ID = (int)newstate;
                            regData[0].IsDraft = IsDraft;//for not show when search 
                            regData[0].T1_UserIdSave = atm_Gen.AppUser.UserID;
                            if (!Client.Tbl_RegistionFactoryUpdate(regData[0]))
                            { msg = string.Format("Tbl_RegistionFactoryUpdate: Save Error"); }
                            else if (!string.IsNullOrEmpty(Remark))
                            {
                                //RemarkID,T1_RegistionID,Detail,RemarkDate,UserID,IsOperation
                                //Remark
                                Tbl_Remark rem = new Tbl_Remark();
                                rem.RemarkDate = System.DateTime.Now;
                                rem.T1_RegistionID = amap.T1_RegistionID;
                                rem.UserID = atm_Gen.AppUser.UserID;
                                rem.Detail = Remark;
                                Client.Tbl_RemarkFactoryInsert(rem);
                            }
                        }
                    }
                }
            }
            return msg;
        }
        
        */


    }


    #region Log
  
    [Serializable()]
    public class atmLog
    {
        public static  atmLog LogAtm = new atmLog();
        public void addlog(string msgData)
        {
            System.IO.StreamWriter logWriter;
            // Code that runs when an unhandled error occurs
            HttpContext ctx = HttpContext.Current;
            if (ctx != null)
            {
                {
                    string msg = msgData;
                    if (msg.Length > 0 && ctx.ApplicationInstance != null)
                    {
                        //Store file name for later use.
                        try
                        {
                            string logName = ctx.ApplicationInstance.Request.PhysicalApplicationPath + "logDebug.txt";

                            //Open file and write information.

                            logWriter = new System.IO.StreamWriter(logName, true);
                            logWriter.WriteLine("Date :" + System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss"));
                            logWriter.WriteLine("Event : " + ctx.ApplicationInstance.Request.CurrentExecutionFilePath);
                            logWriter.WriteLine("LogData : " + msg);
                            logWriter.Flush();
                            logWriter.Close();
                        }
                        catch { }
                    }
                }
                //ctx.ApplicationInstance.Request.CurrentExecutionFilePath
                //ctx.Error.InnerException.Message
            }
        }

    }
    #endregion
    #region Add ValidatorCalloutExtender
    /// <summary>
    /// Sample call form Page_Load
    /// 
    /// setValidate();
    /// atmGen.Validate.CreateValidateControl(this.UpdatePanel1.ContentTemplateContainer, vdlParams);
    /// 
    /// </summary>
    ////private void setValidate()
    ////{
    ////    setValidate(false);
    ////}
    ////private void setValidate(Boolean PageValidate)
    ////{
    ////    List<ValidatorParam> vdlParams = new List<ValidatorParam>();

    ////    string[] errMsg = ("ป้อนรหัสผู้ใช้,,input value first.").Split(',');
    ////    vdlParams.Add(new ValidatorParam(Login1.FindControl("UserNameRequired"), "ป้อนรหัสผู้ใช้", "*"));
    ////    vdlParams.Add(new ValidatorParam(this.FindControl("Login1$PasswordRequired"), "ป้อนรหัสผ่าน", "*"));
    ////    vdlParams.Add(new ValidatorParam(text1, "input value first.", "*cxcxc"));

    ////    atmGen.Validate.CreateValidateControl(this.UpdatePanel1.ContentTemplateContainer, vdlParams);
    ////    if (PageValidate)
    ////    {
    ////        Page.Validate();
    ////    }
    ////}

    #endregion add

    [Serializable()]
    public class Validate
    {
        /// <summary>
        /// Summary description for atmGen
        /// </summary>
        #region Add ValidatorCalloutExtender
        string _HighlightCssClass = "highlight";
        string _NormalStyle = "";
        bool _Force = false;
        public string HighlightCssClass
        {
            get { return _HighlightCssClass; }
            set { _HighlightCssClass = value; }
        }
        public bool Force
        {
            get { return _Force; }
            set { _Force = value; }
        }
        public string NormalStyle
        {
            get { return _NormalStyle; }
            set { _NormalStyle = value; }
        }
        public void AddStyleToControl(Control ctrl, string sstyle)
        {

            if (sstyle.Length > 0)
            {
                string[] attr = sstyle.Split(';');
                foreach (string sty in attr)
                {
                    string[] asty = sty.Split(':');
                    if (asty.GetUpperBound(0) > 0)
                    {
                        if (ctrl.GetType().Equals(typeof(Panel)))
                        {
                            ((Panel)ctrl).Style.Add(asty[0], asty[1]);
                        };
                        if (ctrl.GetType().Equals(typeof(TextBox))) { ((TextBox)ctrl).Style.Add(asty[0], asty[1]); };
                        if (ctrl.GetType().Equals(typeof(Label))) { ((Label)ctrl).Style.Add(asty[0], asty[1]); };
                        //((TextBox)ctrl).Style.Add(asty[0], asty[1]);
                    }
                }
            }

        }

        public void AddRangeValid(ValidatorParam vdlParam)
        {
         //<asp:RangeValidator ID="MyRangeValidator" Display="Static" Type="Currency" MaximumValue="9999999.99"
         //   MinimumValue="0" EnableClientScript="true" ControlToValidate="Text_TotalArea"
         //   runat="server" SetFocusOnError="true" ErrorMessage="กรุณาป้อนจำนวนตัวเลข"></asp:RangeValidator>

            Control TargetControl = vdlParam.TargetControl;
            Control parent = vdlParam.CtrlParent==null ? TargetControl.Parent:vdlParam.CtrlParent;
            string rangeName = "RVLD_" + TargetControl.ID;
            if (!TargetControl.Visible && !Force) { return; }
            if (atm_Gen.SearchControl(parent, rangeName) != null) { return; }
            RangeValidator rvalid = new RangeValidator();
            rvalid.ID = rangeName;
            rvalid.ControlToValidate = TargetControl.ID;
            rvalid.MinimumValue = vdlParam.minimumValue.ToString();
            rvalid.MaximumValue = vdlParam.maximumValue.ToString();
            rvalid.ErrorMessage = vdlParam.errMsg;
            rvalid.Type = vdlParam.rangeType;
            rvalid.Text = vdlParam.Text;
            rvalid.EnableClientScript = true;
            rvalid.Display = ValidatorDisplay.Dynamic;
            rvalid.Visible = true;
            int cnt = parent.Controls.Count;
            for (int ix = 0; ix < cnt; ++ix)
            {
                if (parent.Controls[ix].ClientID == TargetControl.ClientID)
                {
                    try
                    {
                        parent.Controls.AddAt(ix + 1, rvalid);
                    }
                    catch { };
                }
            }
            return;

        }
        public List<Control> CreateValidateControl( List<ValidatorParam> vdlParams)
        {
            List<Control> ControlValidators = new List<Control>();
            //if (parent == null) { return null; }

            
            return ControlValidators;
        }
        private void setTargetControl(Control ControlValidator, Control TargetControl)
        {
            if (ControlValidator == null || TargetControl == null) { return; }
          
        }
    }
        #endregion
    #region Add ValidatorCalloutExtender
    [Serializable()]  
    public class ValidatorParam
    {
        string _valGroup = "";
        string _errMsg = "";
        string _Text = "";
        string _NormalStyle = "";
        double _maximumValue = 99999999.99;
        double _minimumValue = 0;
        ValidationDataType _rangeType = ValidationDataType.Currency;
        bool _isRangeValid = false;
        Control _TargetControl = null;
        Control _ctrlparent = null;
        public ValidatorParam()
        {
        }
        public ValidatorParam(Control CtrlParent, Control TargetControl, string errMsg, string Text, ValidationDataType rangeType)
        {
            pValidatorParam(CtrlParent, TargetControl, errMsg, Text, rangeType, _maximumValue, _minimumValue);
        }
        public ValidatorParam(Control CtrlParent, Control TargetControl, string errMsg, string Text, 
            ValidationDataType rangeType,double MaximumValue,double MinimumValue)
        {
            pValidatorParam(CtrlParent, TargetControl, errMsg, Text, rangeType, MaximumValue, MinimumValue);
        }
        public void pValidatorParam(Control CtrlParent, Control TargetControl, string errMsg, string Text,
            ValidationDataType rangeType, double maximumValue, double minimumValue)
        {
            _isRangeValid = true;
            this._rangeType = rangeType;
            _maximumValue = maximumValue;
            _minimumValue = minimumValue;
            this.CtrlParent = CtrlParent;
            this.TargetControl = TargetControl;
            if (string.IsNullOrEmpty(errMsg))
            {
                this.errMsg = "กรุณาป้อนจำนวนตัวเลข";
            }else
            {
                this.errMsg = errMsg;
            }
            this.Text = Text;
        }
        public ValidatorParam(Control CtrlParent, Control TargetControl, string errMsg, string Text)
        {
            this.CtrlParent = CtrlParent;
            this.TargetControl = TargetControl;
            this.errMsg = errMsg;
            this.Text = Text;
        }
        public ValidatorParam(Control CtrlParent, Control TargetControl, string errMsg, string Text,string ValidGRP)
        {
            this.CtrlParent = CtrlParent;
            this.TargetControl = TargetControl;
            this.errMsg = errMsg;
            this.Text = Text;
            this.ValidateGroupName = ValidGRP;
        }
        public string ValidateGroupName {
            get { return _valGroup; }
            set { _valGroup = value; }
        }
        public bool isRangeValid
        {
            get { return _isRangeValid; }
            set { _isRangeValid = value; }
        }
        public ValidationDataType rangeType
        {
            get { return _rangeType; }
            set { _rangeType = value; }
        }
        public double maximumValue
        {
            get { return _maximumValue; }
            set { _maximumValue = value; }
        }
        public double minimumValue
        {
            get { return _minimumValue; }
            set { _minimumValue = value; }
        }
        public Control CtrlParent
        {
            get { return _ctrlparent; }
            set { _ctrlparent = value; }
        }
        public Control TargetControl
        {
            get { return _TargetControl; }
            set { _TargetControl = value; }
        }
        public string errMsg
        {
            get { return _errMsg; }
            set { _errMsg = value; }
        }
        public string Text
        {
            get { return _Text; }
            set { _Text = value; }
        }
        public string NormalStyle
        {
            get { return _NormalStyle; }
            set { _NormalStyle = value; }
        }
    }
    #endregion
    ///////////////////////////////////////
    #region Data form/database

    [Serializable()]  
    public class PropByName
    {
        object _obj = null;
        public const BindingFlags MemberAccess = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase;
        public PropByName(object obj)
        {
            _obj = obj;
        }
        public object obj
        {
            get { return _obj; }
            set { _obj = value; }
        }
        public object GetValue(string Name)
        {//Ex,Name = "CommandArgument,Text"
            if (_obj == null) { return ""; }
            string[] names = Name.Split(',');
            System.Reflection.PropertyInfo prop = null;
            foreach (string nm in names)
            {
                prop = _obj.GetType().GetProperty(nm, MemberAccess);
                if (prop != null) { break; }
            }
            if (prop == null) { return ""; }
            object ret = prop.GetValue(_obj, null);
            return ret==null?"":ret;
        }
        public object SetValue(string Name, object value)
        {
            if (_obj == null) { return ""; }
            System.Reflection.PropertyInfo prop = _obj.GetType().GetProperty(Name, MemberAccess);
            if (prop == null) { return ""; }
            try
            {
                value = Convert.ChangeType(value, (Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType));
            }
            catch
            {
                value = null;
            }
            prop.SetValue(_obj, value, null);
            return prop.GetValue(_obj, null);
        }
        public List<string> Keys()
        {
            List<string> ls = new List<string>();
            if (_obj == null) { return null; }
            System.Reflection.PropertyInfo[] props = _obj.GetType().GetProperties(MemberAccess);
            foreach (PropertyInfo prop in props)
            {
                ls.Add(prop.Name);
            }
            return ls;
        }
        public List<string> getKetBy(string TableSPName)
        {
            List<string> ls = new List<string>();
//            Type t = new wsv().GetType();
//            System.Reflection.PropertyInfo[] props = t.GetMember(TableSPName).GetType().GetProperties(MemberAccess);
////                Type t = Type.GetType("Tbl_Registion");
//            object new_obj = (object)Activator.CreateInstance(t.GetMember(TableSPName).GetType());
            return ls;
        }
    }
    [Serializable()]  
    public class atmField
    {
        private string _name = string.Empty;
        private object _value = null;

        public atmField()
        {
        }
        public atmField(string name, object value)
        {
            _name = name;
            _value = value;
        }
        public string name
        {
            get { return _name; }
            set { _name = value; }
        }
        public object value
        {
            get { return _value.ToString(); }
            set { _value = value; }
        }
    }

    [Serializable()]  
    public class atmFieldList
    {
        private string _SortName = string.Empty, _SortDirection = string.Empty;
        List<atmField> _data = new List<atmField>();

        public List<atmField> data
        {
            get { return _data; }
        }
        public string SortName
        {
            get { return _SortName; }
            set { _SortName = value; }
        }
        public string SortDirection
        {
            get { return _SortDirection; }
            set { _SortDirection = value; }
        }

        public string getValue(string name)
        {
            //find a specific object
            atmField LocObj = _data.Find(delegate(atmField p) { return p.name == name; });
            if (LocObj == null)
            {
                return "";
            }
            else
            {
                return LocObj.value.ToString();
            }
        }
        public object getValue(string name, Type outType)
        {
            return Convert.ChangeType(getValue(name), outType);
        }
        public int getIValue(string name)
        {
            return int.Parse(getValue(name));
        }
        public DateTime getdateTimeValue(string name)
        {
            string outFormat = "dd/MM/yyyy";
            return getdateTimeValue(name, outFormat);
        }
        public DateTime getdateTimeValue(string name, string outFormat)
        {
            DateTime outdate = new DateTime();
            string txtDatetime = getValue(name);
            //convert string to date time 
            //
            // add code to this .....
            //
            return outdate;
        }
        public object getObj(string name)
        {
            //find a specific object
            atmField LocObj = _data.Find(delegate(atmField p) { return p.name == name; });
            if (LocObj == null) { return ""; }
            else { return LocObj.value; }
        }
        public void setValue(string name, object value)
        {
            //find a specific object
            atmField LocObj = _data.Find(delegate(atmField p) { return p.name == name; });
            if (LocObj == null) { _data.Add(new atmField(name, value)); }
            else { LocObj.value = value; }
        }


    }
    #endregion Data form/database
    #region static class
    [Serializable()]  
    public static class atmData
    {
        public static string getFormValue(object ctrl)
        {
            if (ctrl == null) { return ""; }
            if (ctrl.GetType().IsEnum)
            {
                return Convert.ChangeType(ctrl, typeof(Int64)).ToString();
            }
            else
            {

                Type ty = ctrl.GetType();
                if (ty == typeof(Label))
                { return ((Label)ctrl).Text; }
                else if (ty == typeof(SDSTextBox.SDSTextBox))
                {
                    return ((SDSTextBox.SDSTextBox)ctrl).Text;
                }
                else if (ty == typeof(TextBox) )
                {
                    return ((TextBox)ctrl).Text;
                }
                else if (ty == typeof(DropDownList))
                {
                    return ((DropDownList)ctrl).SelectedValue;
                }
                else if (ty == typeof(RadioButton))
                {
                    return ((RadioButton)ctrl).Checked.ToString();
                }else if(ty == typeof(HiddenField))
                {
                    return ((HiddenField)ctrl).Value.ToString();
                }else if(ty == typeof(RadTextBox)){
                    return ((RadTextBox)ctrl).Text;
                }
                else if (ty == typeof(RadNumericTextBox))
                {
                    return ((RadNumericTextBox)ctrl).Text;
                }
                else if (ty == typeof(RadMaskedTextBox))
                {
                    return ((RadMaskedTextBox)ctrl).Text;
                }
                else if (ty == typeof(RadDatePicker))
                {
                    bool hasValue = ((RadDatePicker)ctrl).SelectedDate.HasValue;
                    return hasValue ? ((DateTime)((RadDatePicker)ctrl).SelectedDate).ToString("dd/MM/yyyy"): "";
                }
                else if (ty == typeof(RadComboBox))
                {
                    return ((RadComboBox)ctrl).SelectedValue;
                }
                else if(ty == typeof(RadButton)){
                    return ((RadButton)ctrl).SelectedToggleStateIndex==0?"true":"false";
                }
                else if (ty == typeof(CheckBox)) 
                {
                    return ((CheckBox)ctrl).Checked ? "true" : "false";
                }
               
            }
            return Convert.ChangeType(ctrl, typeof(string)).ToString();
        }
        public static void setFormValue(object ctrl,object value)
        {
            if (ctrl == null) { return; }
            //if (ctrl.GetType().IsEnum)
            //{
            //    return Convert.ChangeType(ctrl, typeof(Int64)).ToString();
            //}
            //else
            {
                string strValue = value.ToString();
                Type ty = ctrl.GetType();
                if (ty == typeof(Label))
                { ((Label)ctrl).Text = strValue; }
                else if (ty == typeof(TextBox))
                {
                    ((TextBox)ctrl).Text = strValue;
                }
                else if (ty == typeof(RadTextBox))
                {
                    ((RadTextBox)ctrl).Text = strValue;
                }
                else if (ty == typeof(DropDownList))
                {
                    if(((DropDownList)ctrl).Items.FindByValue(strValue)!=null)((DropDownList)ctrl).SelectedValue = strValue;
                }
                else if (ty == typeof(RadComboBox))
                {
                    if (((RadComboBox)ctrl).Items.FindItemByValue(strValue) != null) ((RadComboBox)ctrl).SelectedValue = strValue;
                }
                else if (ty == typeof(RadioButton))
                {
                    ((RadioButton)ctrl).Checked = bool.Parse(strValue);
                }
                else if (ty == typeof(CheckBox))
                {
                    ((CheckBox)ctrl).Checked = bool.Parse(strValue);

                }
                else if (ty == typeof(HiddenField))
                {
                    ((HiddenField)ctrl).Value = strValue;

                }
                else if (ty == typeof(RadDatePicker))
                {
                    ((RadDatePicker)ctrl).SelectedDate = DateTime.Parse(strValue);
                }
                else if (ty == typeof(Button))
                {
                    return;
                }
                else if (ty == typeof(RadButton)) 
                {
                    ((RadButton)ctrl).SelectedToggleState.Value = strValue == null ? "0" : strValue;

                    if (strValue == null || strValue != "2")
                    {
                        ((RadButton)ctrl).ToggleStates[0].Selected = true;

                    }
                    else 
                    {
                        ((RadButton)ctrl).ToggleStates[1].Selected = true;
                    }
                }
                else
                {
                    try
                    {
                        atmGen.PropByName propname = new atmGen.PropByName(ctrl);
                        propname.SetValue("Text", strValue);
                    }
                    catch { };
                }
            }
        }
    }
    #endregion static class
}